<template>
  <div class="app-container">
    <div class="Search">
      <!--工具条-->
      <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
        <el-form :inline="true" :model="query">
          <el-form-item v-has="'PLATFROM_TENANT_QUERY'">
            <el-cascader ref="tenantTree" placeholder="所属租户" :props="tenantProps" :options="tenantOptions" @change="selectTenant" clearable collapse-tags filterable></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-cascader ref="organTree" placeholder="所属组织" :props="props" :options="organOptions" @change="selectOrgan" collapse-tags clearable filterable></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-select v-model="query.params.storeId" clearable placeholder="请选择商铺编号" @change="chooseStore">
              <el-option v-for="item in storeList" :key="item.value" :label="item.storeName" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="query.params.areaId" clearable placeholder="请选择所属区域">
              <el-option v-for="item in areaList" :key="item.id" :label="item.areaName" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="query.params.shelfId" clearable placeholder="请选择货架编号">
              <el-option v-for="item in goodsShelfList" :key="item.id" :label="item.shelfName" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input v-model="query.params.goodsName" placeholder="商品名称" />
          </el-form-item>
          <el-form-item>
            <el-select v-model="query.params.enable" clearable placeholder="是否生效">
              <el-option v-for="item in query.enableOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-date-picker v-model="query.params.expirationTime" format="yyyy-MM-dd" type="daterange" range-separator="至" start-placeholder="过期时间起" end-placeholder="过期时间止">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button v-has="'GOODS_ON_SALE_LIST'" type="primary" icon="el-icon-search" size="mini" @click="fetchData">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button v-has="'GOODS_ON_SALE_ADD'" type="success" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </div>
    <div class="block">
      <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border highlight-current-row>
        <el-table-column align="center" label="序号" width="45">
          <template slot-scope="scope">
            {{ scope.$index }}
          </template>
        </el-table-column>
        <el-table-column label="商品图片" width="110">
          <template slot-scope="scope">
            <el-image style="width: 100px; height: 100px" :src="scope.row.goodsImg">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" width="110">
          <template slot-scope="scope">
            {{ scope.row.goodsName }}
          </template>
        </el-table-column>
        <el-table-column label="货架编号" width="110">
          <template slot-scope="scope">
            {{ scope.row.shelfId }}
          </template>
        </el-table-column>
        <el-table-column label="所属区域" width="110" prop="areaId" :formatter="translateArea" />
        <el-table-column label="所属店铺" width="110" prop="storeId" :formatter="translateStore" />
        <el-table-column label="所属组织" width="110" prop="organId" :formatter="translateOrgan" />
        <el-table-column label="折扣" width="110">
          <template slot-scope="scope">
            {{ scope.row.discount }}
          </template>
        </el-table-column>
        <el-table-column label="折扣价" width="110">
          <template slot-scope="scope">
            {{ scope.row.discountPrice }}
          </template>
        </el-table-column>
        <el-table-column label="是否生效" width="110">
          <template slot-scope="scope">
            {{ scope.row.enable }}
          </template>
        </el-table-column>
        <el-table-column label="过期时间" width="110">
          <template slot-scope="scope">
            {{ scope.row.expirationTime }}
          </template>
        </el-table-column>
        <el-table-column label="商品编号" width="110">
          <template slot-scope="scope">
            {{ scope.row.goodsId }}
          </template>
        </el-table-column>
        <el-table-column label="商品价格" width="110">
          <template slot-scope="scope">
            {{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column label="排序" width="110">
          <template slot-scope="scope">
            {{ scope.row.sorted }}
          </template>
        </el-table-column>
        <el-table-column label="标注" width="110">
          <template slot-scope="scope">
            {{ scope.row.remark }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="created_at" fixed="right" label="操作" width="200">
          <template slot-scope="scope">
            <el-link v-has="'GOODS_ON_SALE_EDIT'" type="warning" icon="el-icon-edit" style="cursor: pointer;" @click="handleEdit(scope.$index, scope.row)">
              修改
            </el-link>
            <el-link v-has="'GOODS_ON_SALE_EDIT'" type="danger" icon="el-icon-delete" style="cursor: pointer;" @click="handleDelete(scope.$index, scope.row)">
              删除
            </el-link>
            <el-link v-has="'STORE_CODE_BAR_ADD'" icon="el-icon-sell" style="cursor: pointer;" type="primary" @click="handleEditBarcode(scope.$index, scope.row)">
              生成条码
            </el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="block">
      <el-pagination :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <div class="block">
      <!--弹框-->
      <el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible">
        <el-form :model="form">
          <el-form-item v-if="addForVisible" label="编号">
            <el-input v-model="form.id" disabled placeholder="编号" auto-complete="off" />
          </el-form-item>
          <el-form-item label="区域编号">
            <el-input v-model="form.areaId" placeholder="区域编号" auto-complete="off" />
          </el-form-item>
          <el-form-item label="商品编号">
            <el-input v-model="form.goodsId" placeholder="商品编号" auto-complete="off" />
          </el-form-item>
          <el-form-item label="商品图片">
            <el-input v-model="form.goodsImg" placeholder="商品图片" auto-complete="off" />
          </el-form-item>
          <el-form-item label="商品名称">
            <el-input v-model="form.goodsName" placeholder="商品名称" auto-complete="off" />
          </el-form-item>
          <el-form-item label="所属组织">
            <el-input v-model="form.organId" placeholder="所属组织" auto-complete="off" />
          </el-form-item>
          <el-form-item label="货架编号">
            <el-input v-model="form.shelfId" placeholder="货架编号" auto-complete="off" />
          </el-form-item>
          <el-form-item label="店铺编号">
            <el-input v-model="form.storeId" placeholder="店铺编号" auto-complete="off" />
          </el-form-item>
          <el-form-item label="商品价格">
            <el-input v-model="form.price" placeholder="商品价格" auto-complete="off" />
          </el-form-item>
          <el-form-item label="折扣">
            <el-input-number v-model="form.discount" :precision="2" :step="0.01" :max="1" style="width: 100%;"></el-input-number>
          </el-form-item>
          <el-form-item label="折扣价">
            <el-input v-model="form.discountPrice" placeholder="折扣价" auto-complete="off" style="width: 100%;" />
          </el-form-item>
          <el-form-item label="是否生效">
            <el-select v-model="form.enable" placeholder="是否生效" style="width: 100%;">
              <el-option v-for="item in query.options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="过期时间">
            <el-date-picker v-model="form.expirationTime" type="date" placeholder="过期时间" style="width: 100%;" />
          </el-form-item>
          <el-form-item label="标注">
            <el-input v-model="form.remark" placeholder="标注" auto-complete="off" />
          </el-form-item>
          <el-form-item label="排序">
            <el-input v-model="form.sorted" placeholder="货架编号" auto-complete="off" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button v-has="'GOODS_ON_SALE_EDIT'" type="primary" @click="handleEditSave">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <el-drawer title="生成条型码" :visible.sync="drawerVisalbe" :direction="direction" :before-close="handleClose" size="50%">
      <div class="demo-drawer__content" style="margin:0 16px 0 16px; height: 100%">
        <el-form :model="storeGoodsBarCode" :rules="storeGoodsBarcodeRules" :label-position="'left'" label-width="100px" ref="storeGoodsBarcodeForm">
          <el-row>
            <el-col :span="12">
              <el-form-item label="条形码"  prop="barCode" style="width: 100%;" required>
                <el-input v-model="storeGoodsBarCode.barCode" placeholder="条形码" auto-complete="off" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="条型码类型"  prop="barCodeType" style="width: 100%;" required>
                <el-select v-model="storeGoodsBarCode.barCodeType" placeholder="条型码类型" @change="createBarcode">
                  <el-option v-for="item in query.barCodeOptions" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="单价"  prop="price" style="width: 100%;" required>
                <el-input-number size="mini" v-model="storeGoodsBarCode.price"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="进货价"  prop="originPrice" style="width: 100%;" required>
                <el-input-number size="mini" v-model="storeGoodsBarCode.originPrice" type="number"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="折扣价"  prop="discountPrice" style="width: 100%;" required>
                <el-input-number size="mini" v-model="storeGoodsBarCode.discountPrice" type="number"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="建议售价"  prop="suggestedRetailPrice" style="width: 100%;" required>
                <el-input-number size="mini" v-model="storeGoodsBarCode.suggestedRetailPrice" type="number"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="成本价"  prop="costPrice" style="width: 100%;" required>
                <el-input-number size="mini" v-model="storeGoodsBarCode.costPrice" type="number"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="库存量"  prop="storeCount" style="width: 100%;" required>
                <el-input-number size="mini" v-model="storeGoodsBarCode.storeCount" type="number"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="条型码图">
                <img id="barcodeImg" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品图">
                <el-image style="width: 100px; height: 100px" :src="storeGoodsBarCode.url" :fit="'fit'"></el-image>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleBarCodeEditSave">确 定</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import { getList, doDelete, doEdit } from '@/api/goodsOnSale/'
import { queryAssigneeOrgan, querySubordinateOrgan } from '@/api/Organ'
import { getStoreList } from '@/api/Store/'
import { queryAreaOfStore, queryAreaOfAll } from '@/api/StoreArea/'
import { queryGoodsShelfOfStore } from '@/api/GoodsShelf/'

import JsBarcode from 'jsbarcode'
import { doEdit as saveStoreGoodsBarcode } from '@/api/storeGoodsBarcode/'
import { getTenantList, getOrganList, getDictionary, translateOrganId2OrganName } from '@/utils/auth'
import { getOrganId, getTenantId, getOrganPath, getCurrentLoginUserId, handleBuildTreeDataStruct, getSelectedNodes, getSelectedNodesObject } from '@/api/utils'
import localStorageUtil from '@/utils/localStorageUtil'

export default {
  data() {
    return {
      list: null,
      listLoading: true,
      total: 5,
      currentPage: 1,
      pageSize: 10,
      dialogFormVisible: false,
      addForVisible: false,
      storeList: [],
      storeMap: null,
      areaList: [],
      areaListAll: [],
      areaMap: null,
      areaMapAll: null,
      goodsShelfList: [],
      goodsShelfMap: null,
      direction: 'rtl',
      drawerVisalbe: false,
      form: {
        areaId: '',
        createBy: '',
        createDate: '',
        discount: '',
        discountPrice: '',
        enable: '',
        expirationTime: '',
        goodsId: '',
        goodsImg: '',
        goodsName: '',
        id: '',
        organId: '',
        organPath: '',
        price: '',
        remark: '',
        shelfId: '',
        sorted: '',
        storeId: '',
        updateBy: '',
        updateDate: ''
      },
      storeGoodsBarCode: {
        id: '',
        storeGoodsId: '',
        tenantId: '',
        parentId: '',
        isDeleted: '',
        barCode: '',
        barCodeType: '',
        organId: '',
        organPath: '',
        createBy: '',
        createDate: '',
        updateBy: '',
        storeId: '',
        updateDate: '',
        remark: '',
        price: '',
        originPrice: '',
        discountPrice: '',
        suggestedRetailPrice: '',
        costPrice: '',
        storeCount: ''
      },
      props: { // 配置项（必选）
        value: 'id',
        label: 'organName',
        children: 'children',
        title: '组织',
        multiple: false,
        checkStrictly: true,
        emitPath: false
        // disabled:true
      },
      organTreeProps: {
        children: 'children',
        label: 'organName',
        url: 'url'
      },
      tenantProps: { // 配置项（必选）
        value: 'id',
        label: 'organName',
        children: 'children',
        title: '租户',
        multiple: false,
        checkStrictly: true,
        emitPath: false
        // disabled:true
      },
      organFormOptions: [],
      tenantOptions: [],
      organOptions: [{ id: '1', parentId: '2', organName: '平台', children: [] }],
      // 新增or编辑弹框标题(根据点击的新增or编辑按钮显示不同的标题)    
      dialogStatus: '',
      optionData: [{ id: '1', parentId: '2', organName: '平台', children: [] }],
      // 新增or编辑弹框标题(根据点击的新增or编辑按钮显示不同的标题)
      titleMap: {
        add: '新增',
        edit: '编辑'
      },
      // 新增和编辑弹框标题
      dialogStatus: '',
      query: {
        params: {
          areaId: '', // 区域编号
          createBy: '', // 添加者
          createDate: '', // 添加时间
          discount: '', // 折扣
          discountPrice: '', // 折扣价
          enable: '', // 是否生效
          expirationTime: '', // 过期时间
          goodsId: '', // 商品编号
          goodsImg: '', // 商品图片
          goodsName: '', // 商品名称
          id: '', // 编号
          organId: '', // 所属组织
          organPath: '', // 组织路径
          price: '', // 商品价格
          remark: '', // 标注
          shelfId: '', // 货架编号
          sorted: '', // 排序
          storeId: '', // 店铺编号
          updateBy: '', // 更新者
          updateDate: '' // 更新时间

        },
        store: {
          addressId: '', // 关联地址
          createBy: '', // 添加者
          createDate: '', // 新增时间
          enable: '', // 是否生效
          id: '', // 主键
          latitude: '', // 纬度
          longitude: '', // 经度
          organId: '', // 所属组织
          organPath: '', // 组织路径
          remark: '', // 标注
          storeName: '', // 店铺名称
          updateBy: '', // 更新者
          updateDate: '', // 更新时间
          total: 0,
          pageSize: 10,
          currentPage: 1
        },
        storeArea: {
          addressId: '',
          tenantId: '',
          areaName: '',
          createBy: '',
          createDate: '',
          url: '',
          enable: '',
          id: '',
          organId: '',
          organPath: '',
          parentId: '',
          remark: '',
          sorted: '',
          storeId: '',
          updateBy: '',
          updateDate: ''
        },
        goodsShelf: {
          id: '' //
            ,
          organId: '' //所属组织
            ,
          areaId: '' //所属区域
            ,
          parentId: '' //父区域
            ,
          shelfName: '' //货架名称
            ,
          sorted: '' //排序字段
            ,
          enable: '' //是否生效
            ,
          addressId: '' //所属地址
            ,
          isDeleted: '' //删除标识
            ,
          createBy: '' //生成者
            ,
          createDate: '' //生成时间
            ,
          updateBy: '' //更新者
            ,
          updateDate: '' //更新时间
            ,
          remark: '' //备注
        },
        timeValue: '',
        enableOptions: [{
          value: '0',
          label: '失效'
        }, {
          value: '1',
          label: '生效'
        }],
        barCodeOptions: [{
          value: 'CODE39',
          label: 'code39'
        }, {
          value: 'CODE128',
          label: 'code128'
        },
        {
          value: 'EAN13',
          label: 'ean13'
        }
      ],
        value: ''
      },
      storeGoodsBarcodeRules:{
        barCode:[
            { required: true, message: '请输入条码', trigger: 'change' }
          ],
          barCodeType:[ { required: true, message: '请选择条码类型', trigger: 'change' }],
          price :[{ required: true,  message: '请输入商品价格', trigger: 'change' }],
          originPrice: [{ required: true,  message: '请输入商品进货价', trigger: 'change' }],
          discountPrice:[{ required: true,  message: '请输入商品折扣价', trigger: 'change' }],
          suggestedRetailPrice:[{ required: true, message: '请输入商品建议价', trigger: 'change' }],
          costPrice:[{ required: true,  message: '请输入商品成本', trigger: 'change' }],
          storeCount:[{ required: true, message: '请填写库存量', trigger: 'change' }]
      }
    }
  },
  created() {
    this.initOrganTree(() => {
      this.setOrganQueryType()
    }, getOrganPath())
    this.initOrganFormTree()
    this.handleFiltTenant()
    this.handleBuildEnableOptions()
    this.handleQueryAreaOfAll()
    this.handleGetStore();
    this.handleQueryGoodsShelfOfArea()
    this.fetchData()
  },
  methods: {
    translateOrgan(row) {
      return translateOrganId2OrganName(row);
    },
    enableFormat(row, column) {

      let label = ''
      for (let i = 0; i < this.query.enableOptions.length; i++) {
        if ('' + row.enable === this.query.enableOptions[i].value) {
          return this.query.enableOptions[i].label
        }
      }
      return label
    },
    fetchData() {
      this.listLoading = true
      this.createOrganQuery()
      this.currentPage =  this.currentPage || 1
      this.pageSize =  this.pageSize || 10 
       getList(this.query.params, this.currentPage, this.pageSize).then(response => {
        const data = response.data
        this.total = data.totalCount
        this.pageSize = data.pageSize
        this.currentPage = data.currentPage
        this.list = data.entities
        this.listLoading = false
      })
    },
    createOrganQuery() {
      // 选中了租户
      let tenantSelected = this.$refs['tenantTree'] && this.$refs['tenantTree'].getCheckedNodes() || []
      let organSelected = this.$refs['organTree'] && this.$refs['organTree'].getCheckedNodes() || []
      let that = this
      this.query.params.organId = null
      if (tenantSelected.length && tenantSelected[0]) {
        this.query.params.tenantId = tenantSelected[0].data.id
        if (organSelected.length && organSelected[0]) {
          if (this.props.multiple) {
            this.query.params.organId = null
            this.query.params.organIds = []
            if (organSelected.length && organSelected[0]) {
              organSelected.forEach(function (element) {
                that.query.params.organIds.push(element.data.id)
              })
            }
          } else if (organSelected.length && organSelected[0]) {
            this.query.params.organPath = organSelected[0] && organSelected[0].data.organPath
          }
        }
      } else {
        this.query.params.tenantId = getTenantId()
        if (organSelected.length && organSelected[0]) {
          if (this.props.multiple) {
            this.query.params.organId = null
            this.query.params.organIds = []
            if (organSelected.length && organSelected[0]) {
              organSelected.forEach(function (element) {
                that.query.params.organIds.push(element.data.id)
              })
            }
          } else if (organSelected.length && organSelected[0]) {
            this.query.params.organPath = organSelected[0].data.organPath
          }
        }

      }
      this.query.params.organId = this.query.params.organId || getOrganId()
      this.query.params.organPath = this.query.params.organPath || getOrganPath()
    },
    handleSizeChange(val) {
      this.currentPage = 1
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    // 新增
    handleAdd() {
      // 显示弹框
      this.dialogFormVisible = true
      // 新增弹框标题
      this.dialogStatus = 'add'

      this.form.areaId = ''
      this.form.createBy = ''
      this.form.createDate = ''
      this.form.discount = ''
      this.form.discountPrice = ''
      this.form.enable = ''
      this.form.expirationTime = ''
      this.form.goodsId = ''
      this.form.goodsImg = ''
      this.form.goodsName = ''
      this.form.id = ''
      this.form.organId = ''
      this.form.organPath = ''
      this.form.price = ''
      this.form.remark = ''
      this.form.shelfId = ''
      this.form.sorted = ''
      this.form.storeId = ''
      this.form.updateBy = ''
      this.form.updateDate = ''
      this.addForVisible = false
    },
    // 编辑
    handleEdit(index, row) {
      console.log(index)
      console.log(row)

      this.form.areaId = row.areaId
      this.form.createBy = row.createBy
      this.form.createDate = row.createDate
      this.form.discount = row.discount
      this.form.discountPrice = row.discountPrice
      this.form.enable = row.enable
      this.form.expirationTime = row.expirationTime
      this.form.goodsId = row.goodsId
      this.form.goodsImg = row.goodsImg
      this.form.goodsName = row.goodsName
      this.form.id = row.id
      this.form.organId = row.organId
      this.form.organPath = row.organPath
      this.form.price = row.price
      this.form.remark = row.remark
      this.form.shelfId = row.shelfId
      this.form.sorted = row.sorted
      this.form.storeId = row.storeId
      this.form.updateBy = row.updateBy
      this.form.updateDate = row.updateDate

      this.addForVisible = true

      // 显示弹框
      this.dialogFormVisible = true
      // 编辑弹框标题
      this.dialogStatus = 'edit'
    },
    handleDelete(index, row) {
      console.log(index)
      console.log(row)

      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        doDelete(row.id).then(response => {
          const gateway = response.data
          let data = gateway.data
          if (data.successful) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.fetchData();
          } else {
            this.$message({
              type: 'info',
              message: data.description || getSystemErrorCode(data.status)
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleEditSave() {
      doEdit(this.form).then(response => {
        const gateway = response.data
        let data = gateway.data
        if (data.successful) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.fetchData();
        } else {
          this.$message({
            type: 'info',
            message: data.description || getSystemErrorCode(data.status)
          })
        }
        this.listLoading = false
        this.dialogFormVisible = false
      })
    },
    handleReset() {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    initOrganTree(fn, filter, that) {
      this.listLoading = true
      let data = getOrganList()
      if (filter) {
        data = data.filter(function(item, index) {
          return item.organPath.indexOf(filter) >= 0
        })
      }
      if (that && that.organFormOptions && that.organFormOptions.length >= 0) {
        that.organFormOptions = handleBuildTreeDataStruct(data, 'id', 'parentId')
      } else {
        this.organOptions = handleBuildTreeDataStruct(data, 'id', 'parentId')
      }
      this.listLoading = false
      if (fn) {
        fn()
      }
    },
    initOrganFormTree(fn, filter) {
      this.initOrganTree(fn, filter, this)
    },
    setOrganQueryType() {
      this.organQueryModelChange(localStorageUtil.fetch("SYSTEM_SETTING_ORGAN_QUERY_MODEL"))
    },
    selectOrgan(nodes) {
      let nodesInfo = this.$refs['organTree'].getCheckedNodes()
      let that = this
      this.query.params.organPath = ''
      this.query.params.organIds = []
      if (this.props.multiple) {
        this.query.params.organIds = []
        if (nodesInfo.length) {
          nodesInfo.forEach(function(element) {
            that.query.params.organIds.push(element.data.id)
          })
        }
      } else if (nodesInfo.length) {
        this.query.params.organPath = nodesInfo[0].data.organPath
      }
    },
    selectTenant(nodes) {
      let nodesInfo = this.$refs['tenantTree'].getCheckedNodes()
      let that = this
      this.query.params.tenantId = ''
      this.query.params.tenantIds = []
      this.query.params.organId = null
      this.query.params.organIds = []
      this.query.params.organPath = null

      if (this.tenantProps.multiple) {
        this.query.params.tenantIds = []
        if (nodesInfo.length) {
          nodesInfo.forEach(function(element) {
            that.query.params.tenantIds.push(element.data.id)
          })
        }
      } else if (nodesInfo.length) {
        this.query.params.tenantId = nodesInfo[0].data.id
        this.initOrganTree(function() {
          that.setOrganQueryType()
        }, nodesInfo[0].data.organPath)
      } else {
        this.initOrganTree(function() {
          that.setOrganQueryType()
        })
      }
    },
    chooseTenantForm(nodes) {
      let nodesInfo = this.$refs['tenantTreeForm'].getCheckedNodes()
      this.form.tenantId = null
      let that = this
      debugger
      if (nodesInfo.length) {
        this.form.tenantId = nodesInfo[0].data.id
        this.initOrganFormTree(function() {
          that.setOrganQueryType()
        }, nodesInfo[0].data.organPath, this.organFormOptions)
      } else {
        this.initOrganFormTree(function() {
          that.setOrganQueryType()
        }, null, this.organFormOptions)
      }
    },
    organQueryModelChange(organQueryModel) {
      if (organQueryModel == 'selected') {
        this.props.multiple = true
      } else if (organQueryModel == 'selfAndSub') {
        this.props.multiple = false
      }
    },
    chooseOrganForm(nodes) {
      let nodesInfo = this.$refs['organTreeForm'].getCheckedNodes()
      if (nodesInfo[0]) {
        this.form.organPath = nodesInfo[0].data.organPath
        this.form.organId = nodesInfo[0].data.id
        this.form.tenantId = nodesInfo[0].data.tenantId
      }
    },
    handleFiltTenant() {
      let data = getOrganList()
      this.tenantOptions = data.filter(function(item, index) {
        return item.type == 0 || item.type == 1;
      })
    },
    handleBuildEnableOptions() {

      const datas = getDictionary()
      let data = datas.filter(function(item, index) {
        return item.bigType === "UserEnable" && item.parentId != '0';
      })
      let enableOptions = [];
      for (let i = 0; i < data.length; i++) {

        let option = {}
        option['value'] = data[i].value
        option['label'] = data[i].desc
        enableOptions.push(option)
      }
      this.query.enableOptions = enableOptions
    },
    handleGetStore() {
      this.listLoading = true
      this.query.store.organPath = this.form.organPath || getOrganPath()
      this.query.store.tenantId = this.form.tenantId || getTenantId()
      getStoreList(this.query.store).then(response => {
        debugger
        const gateway = response.data
        let data = gateway.data
        if (gateway.successful) {
          this.storeList = data
          this.storeMap = {}
          this.handleCreateTranslater(this.storeList, this.storeMap, 'storeName')

        } else {
          this.$message({
            type: 'info',
            message: data.description || getSystemErrorCode(data.status)
          })
        }

        this.listLoading = false
      })
    },

    handleQueryAreaOfStore() {
      this.listLoading = true
      this.query.storeArea.tenantId = this.form.tenantId || getTenantId()
      this.query.storeArea.organId = this.form.organId || getOrganId()
      this.query.storeArea.storeId = this.form.storeId

      queryAreaOfStore(this.query.storeArea).then((res) => {
        debugger
        const data = res.data
        if (data.successful) {
          this.areaList = data.data
          this.areaMap = {}
          this.handleCreateTranslater(this.areaList, this.areaMap, 'areaName')
        } else {
          this.$message({
            type: 'info',
            message: data.description || getSystemErrorCode(data.status)
          })
        }
        this.listLoading = false
      })
    },
    handleQueryAreaOfAll() {
      this.listLoading = true
      this.query.storeArea.tenantId = this.form.tenantId || getTenantId()
      this.query.storeArea.organId = this.form.organId || getOrganId()
      this.query.storeArea.organPath = this.form.organPath || getOrganPath()
      this.query.storeArea.storeId = this.form.storeId

      queryAreaOfAll(this.query.storeArea).then((res) => {
        const gateway = res.data
        if (gateway.successful) {
          this.areaListAll = gateway.data
          this.areaMapAll = {}
          this.handleCreateTranslater(this.areaListAll, this.areaMapAll, 'areaName')
          this.listLoading = false
        } else {
          this.$message({
            type: 'info',
            message: gateway.description || getSystemErrorCode(gateway.status)
          })
          this.listLoading = false
        }

      })

    },
    handleQueryGoodsShelfOfArea() {
      this.listLoading = true
      this.query.goodsShelf.tenantId = this.form.tenantId || getTenantId()
      this.query.goodsShelf.organId = this.form.organId || getOrganId()
      this.query.goodsShelf.organPath = this.form.organPath || getOrganPath()
      this.query.goodsShelf.storeId = this.form.storeId
      this.query.goodsShelf.areaId = this.form.areaId
      queryGoodsShelfOfStore(this.query.goodsShelf).then((res) => {
        const data = res.data
        if (data.successful) {
          this.goodsShelfList = data.data
          this.goodsShelfMap = {}
          this.handleCreateTranslater(this.goodsShelfList, this.goodsShelfMap, 'shelfName')
        } else {
          this.$message({
            type: 'info',
            message: data.description || getSystemErrorCode(data.status)
          })
        }
        this.listLoading = false

      })
    },
    translateStore(row) {
      if (this.storeMap) {
        return this.storeMap[row.storeId];
      }
      this.storeMap = {}
      this.handleCreateTranslater(this.storeList, this.storeMap, 'storeName')
      if (this.storeMap) {
        return this.storeMap[row.storeId] || '';
      }
    },
    translateArea(row) {
      if (this.areaMap) {
        return this.areaMap[row.areaId];
      }
      this.areaMap = {}

      this.handleCreateTranslater(this.areaList, this.areaMap, 'areaName')
      if (this.areaMap) {
        return this.areaMap[row.areaId] || '';
      }
    },
    translateGoodsShelf(row) {
      if (this.goodsShelfMap) {
        return this.goodsShelfMap[row.areaId];
      }
      this.goodsShelfMap = {}

      this.handleCreateTranslater(this.areaList, this.goodsShelfMap, 'shelfName')
      if (this.goodsShelfMap) {
        return this.goodsShelfMap[row.shelfId] || '';
      }
    },

    handleCreateTranslater(list, map, key) {
      if (list && list.length) {
        for (let i = 0; i < list.length; i++) {
          let item = list[i]
          map[item.id] = item[key]
        }
      }
    },
    chooseStore(storeId) {
      this.form.storeId = storeId
      this.handleQueryAreaOfStore()
    },
    chooseArea(areaId) {
      this.form.areaId = areaId
      this.handleQueryGoodsShelfOfArea()
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    handleEditBarcode(index, row) {
      this.drawerVisalbe = true
      this.storeGoodsBarCode.url = row.goodsImg
      this.storeGoodsBarCode.goodsId = row.goodsId
      this.storeGoodsBarCode.storeGoodsId = row.id
      this.storeGoodsBarCode.price = row.price
      this.storeGoodsBarCode.originPrice = row.costPrice
      this.storeGoodsBarCode.discountPrice = row.discountPrice
      this.storeGoodsBarCode.suggestedRetailPrice = row.suggestedRetailPrice
      this.storeGoodsBarCode.costPrice = row.costPrice
      this.storeGoodsBarCode.storeId = row.storeId
      this.storeGoodsBarCode.organId = row.organId || getOrganId()
      this.storeGoodsBarCode.tenantId = row.tenantId || getTenantId()
      this.storeGoodsBarCode.createBy =  getCurrentLoginUserId()
    },
    createBarcode() {
      JsBarcode('#barcodeImg', this.storeGoodsBarCode.barCode, {
        format: this.storeGoodsBarCode.barCodeType, //选择要使用的条形码类型
        width: 1, //设置条之间的宽度
        height: 25, //高度
        displayValue: true, //是否在条形码下方显示文字
        textAlign: "center", //设置文本的水平对齐方式
        textPosition: "bottom", //设置文本的垂直位置
        textMargin: 5, //设置条形码和文本之间的间距
        fontSize: 15, //设置文本的大小
        background: "#eee", //设置条形码的背景
        lineColor: "#2196f3", //设置条和文本的颜色。
        margin: 15 //设置条形码周围的空白边距
      })
    
    },
    handleBarCodeEditSave() {
      this.$refs['storeGoodsBarcodeForm'].validate((valid) => {
          if (valid) {
            saveStoreGoodsBarcode(this.storeGoodsBarCode).then( (res) => {
              const data = res.data
              if (data.successful) {
                console.log(data)
              } else {
                this.$message({
                  type: 'info',
                  message: data.description || getSystemErrorCode(data.status)
                })
              }
              this.listLoading = false
            })
          } else {
            console.log('error submit!!');
            return false;
          }
      });
    }
  }
}

</script>
